import { get, includes } from "lodash";
import axiosLib from "axios";
import createAuthRefreshInterceptor from "axios-auth-refresh";
import { Auth } from "@/services/auth";
import qs from "query-string";
import { restoreSession } from "@/services/restoreSession";
import CryptoJS from 'crypto-js'

// 加密,调用该方法时，传入的data必须是字符串类型，
//   故，如果要加密对象等类型，需要先用JSON.stringify()将其字符串化再传入
// function encryptByAES (data) {
//   let mydata = CryptoJS.enc.Utf8.parse(data)
//   // console.log('key:', key, 'mydata:', mydata)
//   let udata = CryptoJS.AES.encrypt(mydata, key, {
//     mode: CryptoJS.mode.CBC, 
//     iv,
//   })
//   let encrypted = udata.toString()//  返回的是base64的密文,是字符串类型
//   return encrypted
// }
// 解密, 调用该方法时，传入的data是base64的密文
// function decryptByAES (data) {
//   let udata = CryptoJS.AES.decrypt(data, key, {
//     mode: CryptoJS.mode.CBC,
//     iv,
//   })
//   let decrypted = udata.toString(CryptoJS.enc.Utf8)// 返回的是加密之前的原始数据,是字符串类型
//   return decrypted
// }

export const axios = axiosLib.create({
  paramsSerializer: params => qs.stringify(params),
  xsrfCookieName: "csrf_token",
  xsrfHeaderName: "X-CSRF-TOKEN"
});

axios.interceptors.response.use(({ data }) => {
  if (typeof data === 'string') {
    var key = CryptoJS.enc.Utf8.parse('T1FDwKcmz3DvNui0');
    var iv = CryptoJS.enc.Utf8.parse('b3r4z4p1LxMSCoO7');
    let udata = CryptoJS.AES.decrypt(data, key, {
      mode: CryptoJS.mode.CBC,
      iv,
    })
    let result = udata.toString(CryptoJS.enc.Utf8);
    
    try {
      data = JSON.parse(result)
    } catch (error) {
      
    }
  }
  return data
});

export const csrfRefreshInterceptor = createAuthRefreshInterceptor(
  axios,
  error => {
    const message = get(error, "response.data.message");
    if (error.isAxiosError && includes(message, "CSRF")) {
      return axios.get("/ping");
    } else {
      return Promise.reject(error);
    }
  },
  { statusCodes: [400] }
);

export const sessionRefreshInterceptor = createAuthRefreshInterceptor(
  axios,
  error => {
    const status = parseInt(get(error, "response.status"));
    const message = get(error, "response.data.message");
    // TODO: In axios@0.9.1 this check could be replaced with { skipAuthRefresh: true } flag. See axios-auth-refresh docs
    const requestUrl = get(error, "config.url");
    if (error.isAxiosError && (status === 401 || includes(message, "Please login")) && requestUrl !== "api/session") {
      return restoreSession();
    }
    return Promise.reject(error);
  },
  {
    statusCodes: [401, 404],
    pauseInstanceWhileRefreshing: false, // According to docs, `false` is default value, but in fact it's not :-)
  }
);

axios.interceptors.request.use(config => {
  const apiKey = Auth.getApiKey();
  if (apiKey) {
    config.headers.Authorization = `Key ${apiKey}`;
  }

  return config;
});
